/**
 * 主应用组件
 * 
 * 应用的根组件，包含路由配置和全局状态管理
 */

import React, { useEffect } from 'react'
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom'
import { QueryClient, QueryClientProvider } from 'react-query'
import { ReactQueryDevtools } from 'react-query/devtools'

// 导入页面组件
import Layout from '@/components/layout/Layout'
import LoginPage from '@/pages/auth/LoginPage'
import DashboardPage from '@/pages/dashboard/DashboardPage'
import DataSourcesPage from '@/pages/datasources/DataSourcesPage'
import ApiManagementPage from '@/pages/apis/ApiManagementPage'
import MonitoringPage from '@/pages/monitoring/MonitoringPage'
import PluginsPage from '@/pages/plugins/PluginsPage'
import SettingsPage from '@/pages/settings/SettingsPage'
import NotFoundPage from '@/pages/NotFoundPage'

// 导入样式
import '@/globals.css'

// 导入状态管理
import { useUserStore, useSettingsStore } from '@/store'

// 创建React Query客户端
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      retry: 3,
      retryDelay: attemptIndex => Math.min(1000 * 2 ** attemptIndex, 30000),
      staleTime: 5 * 60 * 1000, // 5分钟
      cacheTime: 10 * 60 * 1000, // 10分钟
      refetchOnWindowFocus: false,
    },
    mutations: {
      retry: 1,
    },
  },
})

/**
 * 受保护的路由组件
 * 需要用户登录才能访问
 */
const ProtectedRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { isAuthenticated } = useUserStore()
  
  if (!isAuthenticated) {
    return <Navigate to="/login" replace />
  }
  
  return <>{children}</>
}

/**
 * 主题提供者组件
 * 根据用户设置应用主题
 */
const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { theme } = useSettingsStore()
  
  useEffect(() => {
    const root = window.document.documentElement
    
    // 移除之前的主题类
    root.classList.remove('light', 'dark')
    
    if (theme === 'system') {
      // 系统主题：根据系统偏好设置
      const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
      root.classList.add(systemTheme)
    } else {
      // 用户指定主题
      root.classList.add(theme)
    }
  }, [theme])
  
  return <>{children}</>
}

/**
 * 应用初始化组件
 * 处理应用启动时的初始化逻辑
 */
const AppInitializer: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { token, setUser, logout } = useUserStore()
  
  useEffect(() => {
    // 如果有token，尝试获取用户信息
    if (token) {
      // 这里可以调用API验证token有效性并获取用户信息
      // 暂时跳过，实际项目中需要实现
      console.log('Token found, validating...')
    }
  }, [token, setUser, logout])
  
  return <>{children}</>
}

/**
 * 主应用组件
 */
const App: React.FC = () => {
  return (
    <QueryClientProvider client={queryClient}>
      <ThemeProvider>
        <AppInitializer>
          <Router>
            <div className="min-h-screen bg-background text-foreground">
              <Routes>
                {/* 登录页面 */}
                <Route path="/login" element={<LoginPage />} />
                
                {/* 受保护的路由 */}
                <Route
                  path="/*"
                  element={
                    <ProtectedRoute>
                      <Layout>
                        <Routes>
                          {/* 仪表板 */}
                          <Route path="/" element={<Navigate to="/dashboard" replace />} />
                          <Route path="/dashboard" element={<DashboardPage />} />
                          
                          {/* 数据源管理 */}
                          <Route path="/datasources" element={<DataSourcesPage />} />
                          <Route path="/datasources/:id" element={<DataSourcesPage />} />
                          
                          {/* API管理 */}
                          <Route path="/apis" element={<ApiManagementPage />} />
                          <Route path="/apis/:id" element={<ApiManagementPage />} />
                          
                          {/* 监控面板 */}
                          <Route path="/monitoring" element={<MonitoringPage />} />
                          
                          {/* 插件管理 */}
                          <Route path="/plugins" element={<PluginsPage />} />
                          
                          {/* 系统设置 */}
                          <Route path="/settings" element={<SettingsPage />} />
                          
                          {/* 404页面 */}
                          <Route path="*" element={<NotFoundPage />} />
                        </Routes>
                      </Layout>
                    </ProtectedRoute>
                  }
                />
              </Routes>
            </div>
          </Router>
        </AppInitializer>
      </ThemeProvider>
      
      {/* React Query开发工具 */}
      {import.meta.env.DEV && <ReactQueryDevtools initialIsOpen={false} />}
    </QueryClientProvider>
  )
}

export default App
